package com.xiaolee.hotool.json;

import java.util.ArrayList;
import java.util.List;

public class JsonPathResolver {
    private static final String DEFAULT_DELIMITER = "\\.";
    private String pathStr;
    private String delimiter;

    JsonPathResolver(String pathStr) {
        this.pathStr = pathStr;
        this.delimiter = DEFAULT_DELIMITER;
    }

    List<PathSegment> resolve() {
        List<PathSegment> result = new ArrayList<>();

        String[] paths = pathStr.split(delimiter);
        for (String path : paths) {
            if (path.contains("[")) {
                int leftBound = path.indexOf("[");
                int rightBound = path.indexOf("]");

                PathSegment segment = new PathSegment();
                segment.setArray(true);
                segment.setName(path.substring(0,leftBound));
                segment.setArrayIndex(Integer.parseInt(path.substring(leftBound+1, rightBound)));
                result.add(segment);
            } else {
                PathSegment segment = new PathSegment();
                segment.setArray(false);
                segment.setName(path);
                segment.setArrayIndex(-1);
                result.add(segment);
            }
         }

        return result;
    }
}
